<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
  import echarts from 'echarts'
  require('echarts/theme/macarons') // echarts theme
  import { debounce } from '@/utils'

  export default {
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '300px'
      },
      workorderStatusChart: {
        type: Array,
        default: []
      }
    },
    data() {
      return {
        chart: null,
        chartData: {}
      }
    },
    created() {
      const workorderStatusChart = this.workorderStatusChart
      for (const i in workorderStatusChart) {
        const item = workorderStatusChart[i]
        this.chartData[item.status.toString()] = item.num
      }
    },
    mounted() {
      this.initChart()
      this.__resizeHandler = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHandler)
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      window.removeEventListener('resize', this.__resizeHandler)
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons')

        this.chart.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'right',
            data: ['待处理', '处理中', '已完成', '已放弃']
          },
          calculable: true,
          series: [
            {
              name: 'SQL执行状态',
              type: 'pie',
              // radius: '66%',
              // center: ['50%', '60%'],
              roseType: 'radius',
              radius: [15, 95],
              center: ['40%', '50%'],
              animationEasing: 'cubicInOut',
              data: [
                { value: this.chartData['0'], name: '待处理', itemStyle: { normal: { color: '#0066FF' }}},
                { value: this.chartData['1'], name: '处理中', itemStyle: { normal: { color: '#ab8df2' }}},
                { value: this.chartData['2'], name: '已完成', itemStyle: { normal: { color: '#9bd598' }}},
                { value: this.chartData['3'], name: '已放弃', itemStyle: { normal: { color: '#e14f60' }}}
              ],
              itemStyle: {
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        })
      }
    }
  }
</script>
